package com.google.common.primitives;

public class Bytes {
    public static String toHexString(byte[] bs) {
        return toHexString(bs, false);
    }

    public static String toHexString(byte[] bs, boolean upper) {
        return toHexString(bs, 0, bs.length, upper);
    }

    public static String toHexString(byte[] bs, int start, int len) {
        return toHexString(bs, start, len, false);
    }

    public static String toHexString(byte[] bs, int start, int len, boolean upper) {
        char[] chars = new char[len * 2];
        byte b;
        final int char_a = (upper ? ('A' - 10) : ('a' - 10));
        int end = start + len;
        int j = 0;
        for (int i = start; i < end; i++) {
            b = bs[i];
            byte b1 = (byte) ((b & 0xf0) >> 4);
            byte b2 = (byte) (b & 0x0f);
            chars[j++] = (char) (b1 < 10 ? (b1 + '0') : (b1 + char_a));
            chars[j++] = (char) (b2 < 10 ? (b2 + '0') : (b2 + char_a));
        }
        return new String(chars);
    }

    public static int indexOf(byte[] src, byte b) {
        if (src == null) {
            return -1;
        }
        for (int i = 0; i < src.length; i++) {
            if (src[i] == b) {
                return i;
            }
        }
        return -1;
    }

    public static byte[] append(byte[] src, byte[] append){
        int N = src.length;
        byte[] ret = new byte[N + append.length];
        System.arraycopy(src, 0, ret, 0, N);
        System.arraycopy(append, 0, ret, N, append.length);
        return ret;
    }

    public static boolean equals(byte[] b1, byte[] b2) {
        if (b1 == null && b2 == null) {
            return true;
        }
        if (b1 == null) {
            return false;
        }
        if (b2 == null) {
            return false;
        }
        if (b1.length != b2.length) {
            return false;
        }
        for (int i = 0; i < b1.length; i++) {
            if (b1[i] != b2[i]) {
                return false;
            }
        }
        return true;
    }
}
